package com.shop.service;

import com.shop.model.vo.ESPageInfo;
import com.shop.model.vo.ElasticSearchLog;
import com.shop.model.PageParam;
import com.shop.model.vo.Rsp;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.index.query.*;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * @BelongsProject:  shop
 * @BelongsPackage: com.shop.service
 * @Author: GaoDo
 * @CreateTime: 2020-11-25 14:27
 * @Description:
 */
@Service
public class LogService {

    @Autowired
    @Qualifier("restHighLevelClient")
    private RestHighLevelClient client;


    public Rsp searchSomeLogByPage(PageParam<ElasticSearchLog> pageParam) {
        //搜索索引
        SearchRequest searchRequest = new SearchRequest("logstash");
        //构建搜索
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        //分页
        searchSourceBuilder.from((pageParam.getPageNum()-1)*pageParam.getPageSize());
        searchSourceBuilder.size(pageParam.getPageSize());
        //构建搜索条件 是全部查询还是模糊查询
        //辅助全部查询构造
        MatchAllQueryBuilder matchAllQueryBuilder=null;
        //辅助模糊查询构造属性
        BoolQueryBuilder boolQueryBuilder = null;
        //构造时间范围查询属性
        RangeQueryBuilder rangeQueryBuilder = QueryBuilders.rangeQuery("time");
        BoolQueryBuilder boolBuilder = QueryBuilders.boolQuery();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        try {
            if (!StringUtils.isEmpty(pageParam.getStartDate())) {
                rangeQueryBuilder.gte(sdf.parse(pageParam.getStartDate()).getTime());
            }

            if (!StringUtils.isEmpty(pageParam.getStartDate())) {
                rangeQueryBuilder.lte(sdf.parse(pageParam.getEndDate()).getTime());
            }
            boolBuilder.must(rangeQueryBuilder);
            //must(QueryBuilders.matchQuery("serveTerminal",terminalInfo))

        } catch (Throwable e) {
            e.printStackTrace();
            return Rsp.fail();
        }

        //判断是否为模糊查询
        if(StringUtils.isEmpty(pageParam.getSuperSearchKeyWord())){
            matchAllQueryBuilder = QueryBuilders.matchAllQuery();
        }else{
            //若不为空则构建查询条件
            WildcardQueryBuilder nameQueryBuilder = QueryBuilders.wildcardQuery("name.keyword", "*" + pageParam.getSuperSearchKeyWord() + "*");
            WildcardQueryBuilder ipQueryBuilder = QueryBuilders.wildcardQuery("ip.keyword", "*" + pageParam.getSuperSearchKeyWord() + "*");
            WildcardQueryBuilder uriQueryBuilder = QueryBuilders.wildcardQuery("uri.keyword", "*" + pageParam.getSuperSearchKeyWord() + "*");
            WildcardQueryBuilder requestQueryBuilder = QueryBuilders.wildcardQuery("requestData.keyword", "*" + pageParam.getSuperSearchKeyWord() + "*");
            boolQueryBuilder = new BoolQueryBuilder();
            boolQueryBuilder.should(nameQueryBuilder).should(ipQueryBuilder).should(uriQueryBuilder).should(requestQueryBuilder);
            //最少符合一个条件
            boolQueryBuilder.minimumShouldMatch(1);
        }
        ESPageInfo<ElasticSearchLog> pageInfo = new ESPageInfo<ElasticSearchLog>();
        long total=0;
        //新建一个list把JSON数据转化为对象并存入list集合
        ArrayList<ElasticSearchLog> logArrayList = new ArrayList<>();
        try {
            if(StringUtils.isEmpty(pageParam.getSuperSearchKeyWord())){
                searchSourceBuilder.query(matchAllQueryBuilder);
            }else{
                searchSourceBuilder.query(boolQueryBuilder);
            }
            if(!(StringUtils.isEmpty(pageParam.getStartDate())&&StringUtils.isEmpty(pageParam.getEndDate()))){
            }
            //高亮查询

            //按照时间降序排列
            searchSourceBuilder.sort("time", SortOrder.DESC);
            searchSourceBuilder.timeout(new TimeValue(60, TimeUnit.SECONDS));
            searchRequest.source(searchSourceBuilder);
            SearchResponse response = null;
            response = client.search(searchRequest, RequestOptions.DEFAULT);
            total=response.getHits().getTotalHits().value;
            //获得elasticsearch中的数据
            for (SearchHit hit : response.getHits().getHits()) {
                ElasticSearchLog eslog = new ElasticSearchLog();
                eslog.setIp((String) hit.getSourceAsMap().get("ip"));
                eslog.setName((String) hit.getSourceAsMap().get("name"));
                eslog.setRequestData((String) hit.getSourceAsMap().get("requestData"));
                eslog.setUri((String) hit.getSourceAsMap().get("uri"));
                eslog.setTime(new Date((long)hit.getSourceAsMap().get("time")));
                logArrayList.add(eslog);
            }
        }catch (Exception e) {
            e.printStackTrace();
            return Rsp.fail();
        }
        for (ElasticSearchLog elasticSearchLog : logArrayList) {
            System.out.println(elasticSearchLog);
        }
        pageInfo.setTotal(total);
        pageInfo.setList(logArrayList);
        return Rsp.success(pageInfo);
    }

}
